package com.wugh.fast.module.web.converter;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.wugh.fast.kernel.util.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.beans.PropertyEditorSupport;
import java.util.Date;

/**
 * 说明:
 *
 * @author wugh
 * @date 2019-01-02 18:48
 */
@Slf4j
public class DateConvert extends PropertyEditorSupport {

    @Override
    public String getAsText() {
        Date value = (Date) getValue();
        return value == null ? "" : value.getTime() + "";
    }

    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        if (StringUtils.isNotBlank(text)) {
            try {
                DateTime dateTime = DateUtil.parse(text);
                setValue(dateTime.toJdkDate());
            } catch (Exception e) {
                //报错,则可能是纯数字的时间戳
                try {
                    setValue(new Date(Long.parseLong(text)));
                } catch (NumberFormatException ex) {
                    log.debug("日期转换失败:{}", text);
                }
            }
        }
    }
}
